require( '$d/css/common.less' );
require( './style.less' );
define( [
  'require',
  'jquery',
  'header',
  'bigwe_utils',
  'pagination',
  'message',
  'constants',
  'artCategoryHandle',
  'combiner',
  'selector',
  'constants'
], function( require, $ ) {
  var util = require( 'bigwe_utils' ),
    ShowTitleMessage = require( 'message' ),
    route = require( 'constants' ),
    category = require( 'artCategoryHandle' ),
    constants = require( 'constants' );
  var getQueryStr = util.getUrlParam( "tag" );

  $( '.selectpicker' ).selectpicker();
  var content = $( '.main-content' ),
    tags_cd = content.find( '#cat_cds' ).val().split( ',' ),
    myAjax = function( options ) {
      var defaults = {
        type: 'post', //请求的方法,默认为post
        beforefn: ShowTitleMessage.show( '正在加载...' ),
      };
      var opt = $.extend( {}, defaults, options );
      $.ajax( {
        type: opt.type,
        url: opt.url || '',
        data: opt.data || '',
        dataType: opt.dataType || 'json',
        before: function() {
          opt.beforefn || '';
        },
        success: function( data ) {
          var data = ( typeof data === 'string' ) ? $.parseJSON( data ) : data;
          if ( $.isFunction( opt.callBack ) ) {
            opt.callBack( data );
          }
        },
        error: function( XMLHttpRequest, textStatus, errorThrown ) {
          console.log( textStatus );
          console.log( XMLHttpRequest.status );
          console.log( XMLHttpRequest.readyState );
        },
      } )
    }
    /*
     * ===== * 文章关注领域加载 * =====
     */
  for ( key in tags_cd ) {
    if ( tags_cd[ key ] != '' ) $( ".article-tag" ).append( '<span data-ca="' + tags_cd[ key ] + '">' + category.category[ tags_cd[ key ] ] + '</span>' );
  }

  content.find( '.main-title >  span' ).text( getQueryStr );

  var param = {
    url: '/search/get_art_ls4s',
    data: {
      p: 1,
      tag: getQueryStr,
    },
    callBack: tag_list,
    page: true,
    // beforefn: ShowTitleMessage.show( '正在加载...' ),
  };

  myAjax( param );

  function tag_list( data ) {
    var data = typeof data === 'string' ? $.parseJSON( data ) : data,
      arts = data.data.articles,
      arts_html = '',
      tal_num = 0;

    if ( arts.length > 0 ) {
      tal_num = data.data.total_number;
      var cds = '';
      for ( var key in arts ) {
        var art = arts[ key ];
        // 平台标识
        var source_icon = '';
        if ( art.source == 'bigwe.com' ) {
          source_icon = 'icon-iconbigwe'
        } else if ( art.source == 'toutiao.com' ) {
          source_icon = 'icon-icontoutiao'
        } else if ( art.source == 'news.163.com' ) {
          source_icon = 'icon-wangyi'
        } else if ( art.source == 'news.sina.com.cn' ) {
          source_icon = 'icon-xinlang'
        } else if ( art.source == 'ifeng.com' ) {
          source_icon = 'icon-ifeng'
        } else if ( art.source == 'mp.weixin.qq.com' ) {
          source_icon = 'icon-weixin'
        }

        //原创标识
        var cs = art.copyright_stat * 1;
        var copyright_img = '';
        if ( cs == 1 || cs == 2 ) {
          if ( art.source == 'toutiao.com' ) {
            copyright_img = '<span class="toutiao_copyright">原创</span>';
          } else if ( art.source == 'bigwe.com' ) {
            copyright_img = '<img src="/Public/static/images/original1.png" alt="" class="original"/>';
          } else if ( art.source == 'mp.weixin.qq.com' ) {
            copyright_img = '<img src="/Public/static/images/original2.png" alt="" class="original"/>';
          }
        }

        arts_html += '<div class="article-sub">' +
          ' <div class="article-title"><a href="/article?p=' + art.cd + '" target="_blank">' + art.title + '</a></div>' +
          '<p id="' + art.cd + '">阅读:<span>0</span>点赞:<span>0</span></p>';

        var img_url = constants.surpportHostName + '/timthumb.php?w=130&src=' + art.cover_img_url;
        if ( art.cover_img_url ) {
          arts_html += '<div class="picture">' +
            '<a href="/article?p=' + art.cd + '" target="_blank"><img src="' + img_url + '" alt="" onerror="this.src=\'' + route.resPath + '/images/wuyulantu2.png\';"></a>' + copyright_img +
            '</div>';
        }

        arts_html += '<div class="article-sub-taxt ' + ( ( art.cover_img_url ) ? 'cartons' : 'cartons_fluid' ) + '" data-articleid="' + art.cd + '" data-title="' + art.title + '" data-img="' + data.data.img_cdn + art.cover_img_url + '" data-url="/article?p=' + art.cd + '" data-id="' + art.cd + '">' +
          '<p>' + ( ( art.summary == "" || art.summary == null ) ? '' : art.summary ) + '</p>';
        if ( art.source == 'mp.weixin.qq.com' ) {
          arts_html += '<div class="btn_plat btn_plat_wx" onclick="window.open(\'/profile?biz=' + util.getUrlParam( art.source_url, '__biz' ) + '&gn=' + art.publisher + '&platform=' + art.source + '\')">'
        } else {
          arts_html += '<div class="btn_plat">'
        }
        arts_html += '<span class="iconfont platform-icon ' + source_icon + '"></span>' +
          '<span class="article-account">' + art.publisher + '</span></div>' +
          '<span class="article-time">' + ( new Date( art.publish_time_millis * 1 ) ).format( 'yyyy-MM-dd hh:mm' ) + '</span>' +
          '		 <span class="tag">标签:</span>';
        var tags = ( art.tags == null || art.tags == "" || typeof( art.tags ) == "undefined" ) ? '' : art.tags.replace( /\[|\]/g, '' ).split( ',' );
        for ( var i = 0; i < tags.length; i++ ) {
          arts_html += '<a class="green" href="/tag_preview?p=1&tag=' + tags[ i ].trim() + '">' + tags[ i ].trim() + '</a>';
        };
        arts_html += '<span class="iconfont article-collect icon-Collect"></span>' +
          '<span class="iconfont article-merge icon-box" addcar-event></span>' +
          '</div></div>';
        if ( cds.length > 1 ) {
          cds += ','
        }
        cds += art.cd;
      }
    } else {
      arts_html = '<p>没有相关连的素材！</p>';
    }
    content.find( '.total_number' ).html( tal_num );
    content.find( '.article-list' ).empty().append( arts_html );
    paging( tal_num );
    ShowTitleMessage.hide();
    /*文章点赞数和阅读数*/
    if ( cds ) {
      $.get( 'assets/get_msg_ext?cd=' + cds.substring( 1 ), function( obj ) {
        var items = obj.data;
        for ( var i in items ) {
          var item = items[ i ];
          var read_item = $( '#' + item.cd + '>span:first-child' );
          var like_item = $( '#' + item.cd + '>span:last-child' );
          read_item.text( read_item.text() * 1 + item.read_num * 1 );
          like_item.text( like_item.text() * 1 + item.like_num * 1 );
        }
      } );
    }
  }

  function paging( total ) {
    var page = ( total > 500 ) ? '500' : total;
    if ( page > 10 ) {
      content.find( '.paging' ).show();
    } else {
      content.find( '.paging' ).hide();
    }
    if ( param.page ) {
      content.find( ".paging" ).pagination( page, {
        num_edge_entries: 0,
        items_per_page: 10,
        prev_text: '上一页',
        next_text: '下一页',
        callback: function( page_index, jq ) {
          if ( param.page ) {
            param.page = false;
            return;
          } else {
            param.data.p = page_index + 1;
            myAjax( param );
          }
        }
      } );
    }
  }

  /*
   * ========== * 关注领域 * ==========
   */
  content.find( ".article-tag" ).on( "click", "span", function() {
    $( this ).addClass( "green" ).siblings().removeClass( "green" );
    param.data.ca = $( this ).data( 'ca' );
    param.data.p = 1;
    param.page = true;
    myAjax( param );
  } );

  /*
   * ========== * 筛选 * ==========
   */
  var filter_selection = content.find( '.filter_selection' );
  filter_selection.on( 'click', '.filter-btn', function() {
    $( '.selectpicker' ).selectpicker();
    var $this = $( this ),
      _t = $this.data( 'show' );
    if ( _t ) {
      $this.siblings( ".filter-select" ).hide();
      $this.find( "span:last-child" ).text( "展开筛选" );
      $this.find( "span:first-child" ).addClass( "glyphicon-filter" ).removeClass( "glyphicon-menu-up" );
      $this.attr( 'data-show', false ).data( 'show', false );
    } else {
      $this.siblings( ".filter-select" ).show();
      $this.find( "span:first-child" ).removeClass( "glyphicon-filter" ).addClass( "glyphicon-menu-up" );
      $this.find( "span:last-child" ).text( "收起筛选" );
      $this.attr( 'data-show', true ).data( 'show', true );
    }
  } );
  filter_selection.on( 'change', 'select', function() {
    var val = $( this ).val();
    var name = $( this ).attr( 'name' );

    param.data.p = 1;
    param.data[ name ] = val;
    param.page = true;
    myAjax( param );
  } );
  /*收藏*/
  // content.on( "click", ".article-collect", function() {
  // 	$( this ).addClass( "icon_selected" );
  // 	var re = $( this );
  // 	var articleID = $( this ).parent().attr( 'data-articleID' );
  // 	$.get( '/favorites/add', {
  // 			cd: articleID,
  // 			rt: "collectArt",
  // 		},
  // 		function( data ) {
  // 			data = apinput( data );
  // 			if ( data != 44444 ) {
  // 				ShowTitleMessage.show( '收藏成功!', 1000 );
  // 			} else {
  // 				re.removeClass( "icon_selected" );
  // 			}
  // 		} );
  // } );
  // content.on('click','.search_btn',function() {
  // 	param.data.key = $( '#search_text' ).val();
  // 	param.data.p = 1;
  // 	param.page = true;
  // 	myAjax(param);
  // } )
} )